package cn.hdu.liang.first;

import cn.hdu.liang.po.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MybatisFirst {

    //得到配置文件流
    InputStream inputStream;
    SqlSessionFactory sqlSessionFactory;
    SqlSession sqlSession;

    {
        try {
            inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch(IOException e) {
            e.printStackTrace();
        }
        //创建会话工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //通过工厂得到SqlSession
        sqlSession = sqlSessionFactory.openSession();
    }

    //根据id查询用户信息，得到一条数据的结果
    @Test
    public void findUserByIdTest() {
        User user = sqlSession.selectOne("test.findUserByName", 10);
        System.out.println(user);
    }

    @Test
    public void findUserByNameTest() {
        List<User> list = sqlSession.selectList("test.findUserByName", "小明");
        System.out.println(list);
    }

    @Test
    public void insertUserTest() {
        User user = new User();
        user.setUsername("梁惠兵");
        user.setBirthday(new Date());
        user.setSex("1");
        user.setAddress("河北石家庄");

        sqlSession.insert("test.insertUser", user);

        sqlSession.commit();
        System.out.println(user.getId());
    }

    @Test
    public void deleteUser() {
        sqlSession.delete("test.deleteUser", 33);
        sqlSession.commit();
    }

    @Test
    public void updateUser() {
        User user = sqlSession.selectOne("test.findUserById", 32);
        user.setUsername("金三胖");
        sqlSession.update("test.updateUser", user);
        sqlSession.commit();
    }

}
